package com.star.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * @author tanyapeng
 * @date 2021/2/8
 */
public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {

    private final static ZoneId ZONE = ZoneId.of("GMT+8");

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setObject(i, parameter);
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp sqlTimestamp = rs.getTimestamp(columnName);
        if (sqlTimestamp != null) {
            return LocalDateTime.ofInstant(Instant.ofEpochMilli(sqlTimestamp.getTime()), ZONE);
        }
        return null;
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = rs.getTimestamp(columnIndex);
        if (sqlTimestamp != null) {
            return LocalDateTime.ofInstant(Instant.ofEpochMilli(sqlTimestamp.getTime()), ZONE);
        }
        return null;
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = cs.getTimestamp(columnIndex);
        if (sqlTimestamp != null) {
            return LocalDateTime.ofInstant(Instant.ofEpochMilli(sqlTimestamp.getTime()), ZONE);
        }
        return null;
    }
}
